#!/usr/bin/env python
#coding=utf-8

import os
import json
import yaml
import logging
from pprint import pprint
from kubernetes import client
from core.logger import logger

class K8sPod(object):

    def __init__(self):
        self.apps_v1 = client.CoreV1Api()


    def delete_pod_from_namespace(self, namespace_name,pod_name):
        try:
            resp = self.apps_v1.delete_namespaced_pod(namespace=namespace_name,name=pod_name)
            # pprint(resp)
        except Exception as e:
            logger.error(f"delete pod {namespace_name}:{pod_name} error=>{e}")
            return False

        return True

    def list_namespaced_pod(self, namespace_name):
        """
        获得命名空间下所有的pods信息
        """
        try:
            resp = self.apps_v1.list_namespaced_pod(namespace=namespace_name)
        except Exception as e:
            logger.error(f"list pod {namespace_name} error=>{e}")
            return None

        return resp.items


    def list_node_pod(self, node_name, namespace_name=None):
        """
        过滤出节点上的pods信息
        """
        try:
            # 构造查询的字段选择器
            field_selector = f"spec.nodeName={node_name}"
            if namespace_name:
                field_selector += f",metadata.namespace={namespace_name}"

            # 使用客户端获取节点上的 Pod 列表
            resp = self.apps_v1.list_pod_for_all_namespaces(field_selector=field_selector)
            
            # 打印每个 Pod 的信息
            # for pod in resp.items:
            #     print(f"Pod Name: {pod.metadata.name}\tNamespace: {pod.metadata.namespace}\tStatus: {pod.status.phase}")
        except Exception as e:
            logger.error(f"list pod {node_name}:{namespace_name} error=>{e}")
            return None

        return resp.items